<?php
/**
 * Created by PhpStorm.
 * User: bob
 * Date: 21/3/30
 * Time: 上午10:37
 */

namespace App\Api\Account\Controllers;


use App\Api\Account\Models\BusinessInfo;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BusinessController extends Controller
{
    /**
     * 银行信息
     * @param Request $request
     * @return array
     */
    public function bankIndex(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $businessInfo = BusinessInfo::where('user_id', '=', $user->id)
            ->first();

        if (empty($businessInfo)) {
            return $this->formatOutput(['bank' => '', 'bank_person' => '', 'bank_account' => '']);
        }

        return $this->formatOutput($businessInfo->toArray());
    }

    /**
     * 银行信息更新
     * @param Request $request
     * @return array
     */
    public function bankUpdate(Request $request)
    {
        $params = $request->all();
        $user = authUser();
        $array = [];
        $bank = data_get($params, 'bank', '');
        $bankPerson = data_get($params, 'bank_person', '');
        $bankAccount = data_get($params, 'bank_account', '');
        $smsCodeMobile = data_get($params, 'mobile', '');
        $smsCode = data_get($params, 'sms_code', '');

        if (!empty($bank)) {
            $array['bank'] = $bank;
        }

        if (!empty($bankPerson)) {
            $array['bank_person'] = $bankPerson;
        }

        if (!empty($bankAccount)) {
            $array['bank_account'] = $bankAccount;
        }
        $savedSmsCode = \Cache::get($smsCodeMobile);
        if (!$savedSmsCode) {
            throw new \LogicException('验证码已失效, 请重新获取', 20);
        }
        if ($savedSmsCode != $smsCode) {
            throw new \LogicException('验证码错误', 30);
        }

        $businessInfo = BusinessInfo::where('user_id', '=', $user->id)
            ->first();

        if (empty($businessInfo)) {
            BusinessInfo::create($array);
        } else {
            $businessInfo->update($array);
        }
        \Cache::forget($smsCodeMobile);

        return $this->formatOutput('success');
    }
}
